package cn.attackme.myuploader.utils;

import cn.attackme.myuploader.model.ExcelContent;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.itit.itf.okhttp.FastHttpClient;
import org.springframework.beans.factory.annotation.Value;

import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Classname OCR
 * @Description TODO
 * @Date 2021/4/21 0021 14:12
 * @Created by xz8090
 */
public class OCR {

    //普通电子发票属于类型1，增值税普通发票属于类型2，增值税专用发票属于类型3
    public static int getType(JSONArray data){
        for (int i=0;i<data.size();i++){
            JSONObject oneResult = data.getJSONObject(i);
            String text = oneResult.get("text").toString().replaceAll(" ","");
            if(text.contains("发票代码")) return 1;
        }
        return 0;
    }

    public static ExcelContent getResult(String http, String jsonStr){
        try{
            String result = doPost(http,jsonStr);
            JSONObject jsonObject = JSON.parseObject(result);
            if(jsonObject.get("errCode").equals(0)){
                JSONArray data = jsonObject.getJSONArray("data");
                String code = "";//发票代码
                String num = "";//发票号码
                String time = "";//发票时间
                String check = "";//校验码
                String name = "";//开票方名称
                String price = "";//金额
                String tax = "";//税额
                String sum = "";//总计
                int type = getType(data);
                if(type==1) {
                    //发票代码匹配
                    String pattern = "(发票代码:\\d{12})";
                    String pattern2 = "(发票代码\\d{12})";
                    Pattern r = Pattern.compile(pattern);
                    Pattern r2 = Pattern.compile(pattern2);
                    for (int i = 0; i < data.size(); i++) {
                        JSONObject oneResult = data.getJSONObject(i);
                        String text = oneResult.get("text").toString().replaceAll(" ", "");
                        if(text.contains("发票代码")) text = text.replaceAll("o","0").replaceAll("O","0");
                        Matcher m = r.matcher(text);
                        Matcher m2 = r2.matcher(text);
                        if (m.find()){
                            code = m.group(1).replace("发票代码:","");
                            //System.out.println("发票代码："+code);
                            break;
                        }else if (m2.find()){
                            code = m2.group(1).replace("发票代码","");
                            //System.out.println("发票代码："+code);
                            break;
                        }
                    }
                    //发票号码
                    pattern = "(发票号码:\\d{8})";
                    pattern2 = "(发票号码\\d{8})";
                    r = Pattern.compile(pattern);
                    r2 = Pattern.compile(pattern2);
                    for (int i = 0; i < data.size(); i++) {
                        JSONObject oneResult = data.getJSONObject(i);
                        String text = oneResult.get("text").toString().replaceAll(" ", "");
                        if(text.contains("发票号码")) text = text.replaceAll("o","0").replaceAll("O","0");
                        Matcher m = r.matcher(text);
                        Matcher m2 = r2.matcher(text);
                        if (m.find()){
                            num = m.group(1).replace("发票号码:","");
                            //System.out.println("发票号码："+num);
                            break;
                        }else if (m2.find()){
                            num = m2.group(1).replace("发票号码","");
                            //System.out.println("发票号码："+num);
                            break;
                        }
                    }
                    //校验码
                    pattern = "(校验码:\\d{20})";
                    pattern2 = "(校验码\\d{20})";
                    r = Pattern.compile(pattern);
                    r2 = Pattern.compile(pattern2);
                    for (int i = 0; i < data.size(); i++) {
                        JSONObject oneResult = data.getJSONObject(i);
                        String text = oneResult.get("text").toString().replaceAll(" ", "");
                        if(text.contains("校验码")) text = text.replaceAll("o","0").replaceAll("O","0");
                        Matcher m = r.matcher(text);
                        Matcher m2 = r2.matcher(text);
                        if (m.find()){
                            check = m.group(1).replace("校验码:","");
                            //System.out.println("校验码："+check);
                            break;
                        }else if (m2.find()){
                            check = m2.group(1).replace("校验码","");
                            //System.out.println("校验码："+check);
                            break;
                        }
                    }

                }else{
                    //增值税共有判断
                    //发票代码匹配
                    String pattern = "(\\d{10})";
                    Pattern r = Pattern.compile(pattern);
                    for (int i = 0; i < data.size(); i++) {
                        JSONObject oneResult = data.getJSONObject(i);
                        String text = oneResult.get("text").toString().replaceAll(" ", "");
                        Matcher m = r.matcher(text);
                        if (m.find()) {
                            code = m.group(1);
                            check = code;
                            System.out.println("发票代码：" + code);
                            break;
                        }
                    }
                    //发票号码
                    pattern = "(N\\d{8})";
                    String pattern2 = "(\\d{8})";
                    r = Pattern.compile(pattern);
                    Pattern r2 = Pattern.compile(pattern2);
                    String f1 = "";
                    String f2 = "";
                    for (int i = 0; i < data.size(); i++) {
                        JSONObject oneResult = data.getJSONObject(i);
                        String text = oneResult.get("text").toString().replaceAll(" ", "");
                        Matcher m = r.matcher(text);
                        if (m.find()) {
                            f1 = m.group(1).replace("N", "");
                            break;
                        }
                    }
                    for (int i = 0; i < data.size(); i++) {
                        JSONObject oneResult = data.getJSONObject(i);
                        String text = oneResult.get("text").toString().replaceAll(" ", "");
                        Matcher m2 = r2.matcher(text);
                        if (m2.find()) {
                            f2 = m2.group(1);
                            break;
                        }
                    }
                    if (f1.equals(f2)) num = f1;

                }
                //发票时间
                String pattern = "(日期:[0-9]{8})";
                String pattern2 = "(日期[0-9]{8})";
                Pattern r = Pattern.compile(pattern);
                Pattern r2 = Pattern.compile(pattern2);
                for (int i = 0; i < data.size(); i++) {
                    JSONObject oneResult = data.getJSONObject(i);
                    String text = oneResult.get("text").toString().replaceAll(" ", "").replace("年","").replace("月","");
                    if(text.contains("日期")) text = text.replaceAll("o","0").replaceAll("O","0");
                    text = new StringBuilder(text).reverse().toString().replaceFirst("日","");
                    text = new StringBuilder(text).reverse().toString();
                    Matcher m = r.matcher(text);
                    Matcher m2 = r2.matcher(text);
                    if (m.find()) {
                        time = m.group(1).replace("日期:", "");
                        time = time.substring(0,4)+"/"+time.substring(4,6)+"/"+time.substring(6);
                        //System.out.println("发票日期：" + time);
                        break;
                    } else if (m2.find()) {
                        time = m2.group(1).replace("日期", "");
                        time = time.substring(0,4)+"/"+time.substring(4,6)+"/"+time.substring(6);
                        //System.out.println("发票日期：" + time);
                        break;
                    }
                }

                //金额、税额、合计
                pattern = "(([¥]|[￥])[0-9]{1,8}.[0-9]{1,2})";
                r = Pattern.compile(pattern);
                boolean getprice = false;
                boolean gettax = false;
                for (int i = 0; i < data.size(); i++) {
                    JSONObject oneResult = data.getJSONObject(i);
                    String text = oneResult.get("text").toString().replaceAll(" ", "");
                    if(text.contains("￥")) text = text.replace("(","").replace(")","").replaceAll("o","0").replaceAll("O","0");
                    Matcher m = r.matcher(text);
                    if (m.find()){
                        if(getprice){
                            if(gettax){
                                if(text.contains("小写")){
                                    String maysum = m.group(1).replace("￥", "");
                                    BigDecimal d1 = new BigDecimal(price);
                                    BigDecimal d2 = new BigDecimal(tax);
                                    BigDecimal d3 = new BigDecimal(maysum);
                                    if( d1.add(d2).equals(d3) ) {
                                        sum = maysum;
                                        break;
                                    }
                                }
                            }else {
                                if(text.contains("小写")) break;//说明前面金额和税收有一个漏了
                                tax = m.group(1).replace("￥", "");
                                //有可能两者反了,就交换位置
                                if(Double.parseDouble(price)<Double.parseDouble(tax)){
                                    String temp = tax;
                                    tax = price;
                                    price = temp;
                                }
                                //System.out.println("金额：" + price);
                                //System.out.println("税额：" + tax);
                                gettax = true;
                            }
                        }else {
                            price = m.group(1).replace("￥", "");
                            getprice = true;
                        }
                    }
                }
                //开票方名称
                boolean fistname = false;//收票方名称是否过滤
                pattern = "(称:[\\u4e00-\\u9fa5]+)";
                r = Pattern.compile(pattern);
                for (int i = 0; i < data.size(); i++) {
                    JSONObject oneResult = data.getJSONObject(i);
                    String text = oneResult.get("text").toString().replaceAll(" ", "");
                    Matcher m = r.matcher(text);
                    if (m.find()){
                        if(fistname){
                            name = m.group(1).replace("称:", "");
                            //System.out.println("开票方名称：" + name);
                            break;
                        }else {
                            String firstname = m.group(1).replace("称:", "");
                            //System.out.println("收票方名称：" + firstname);
                            fistname = true;
                        }
                    }
                }
                ExcelContent excelContent = new ExcelContent(code,num,time,check,name,price,tax,sum);
                return excelContent;
            }
        }catch(Exception e){}
        return null;
    }

    public static String doPost(String url,String jsonStr) throws Exception {
        return FastHttpClient.post().addHeader("Content-Type","application/json").
                body(jsonStr).
                url(url).
                build().
                execute().string();
    }
}
